import plugin from '../../../lib/plugins/plugin.js'
import {segment} from "oicq"
import _ from "underscore"
import Yaml from '../Yaml/Yaml.js'

const commonErrorMsg = '别闹~'

let rootPath = process.cwd()
let pluginPath = rootPath + '/plugins/fisticuffs-plugin/config/'
let appConfigPath = pluginPath + 'application.yaml'
let mainOtherConfigPath = './config/config/other.yaml'

export class admin extends plugin {
    constructor() {
        super({
            name    : '超级用户管理',
            dsc     : '超级用户管理',
            event   : 'message',
            priority: 4996,
            rule    : [
                {
                    reg: '^设置绝对权限$',
                    fnc: 'setAbsoluteMaster',
                },
                {
                    reg: '^主人列表$',
                    fnc: 'getMaster',
                },
                {
                    reg: '^增加主人.*$',
                    fnc: 'addMaster',
                },
                {
                    reg: '^删除主人.*$',
                    fnc: 'delMaster',
                },
                {
                    reg: '^删除所有主人$',
                    fnc: 'delAllMaster',
                },
                {
                    reg: '^查看互殴设置$',
                    fnc: 'getConfig',
                },
            ],
        });
    };

    // 设置绝对权限
    async setAbsoluteMaster(e) {

        // 群聊不能设置，防止和别人的机器人指令冲突
        if (e.isGroup) {
            return false
        }

        // 非master不能设置，防止被路人误设置
        if (!e.isMaster) {
            e.reply(`身份验证失败~`)
            return false
        }

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster

        if (absoluteMaster > 0) {
            if (absoluteMaster === e.user_id) {
                e.reply(`主人有什么吩咐~`)
            } else {
                e.reply(`绝对权限被设置了~`)
            }
            return false
        }

        appConfig.absoluteMaster = e.user_id

        Yaml.write(appConfigPath, appConfig)

        let msg = ''
        msg += '---------------------------------\n'
        msg += '  绝对权限设置成功~\n'
        msg += '---------------------------------\n'
        msg += '  权限指令示例：\n'
        msg += '【主人列表】\n'
        msg += '【增加主人123456】\n'
        msg += '【删除主人@大黄@喵喵】\n'
        msg += '【删除所有主人】\n'
        msg += '---------------------------------\n'
        msg += '  权限指令说明：\n'
        msg += '增加删除的@支持多人\n'
        msg += '删除所有主人指除你之外的所有人\n'
        msg += '---------------------------------\n'

        e.reply(msg)

        return false;
    }

    // 主人列表
    async getMaster(e) {

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster

        if (e.user_id !== absoluteMaster) {
            if (!e.isGroup) {
                e.reply(`身份验证失败~`)
            }
            return false
        }

        let masterQQList = await Yaml.read(mainOtherConfigPath).masterQQ

        let msg = ''
        for (let v = 0; v < masterQQList.length; v++) {
            msg += `${v + 1}.` + masterQQList[v] + '\n'
        }

        let nickname = Bot.nickname
        if (e.isGroup) {
            let info = await Bot.getGroupMemberInfo(e.group_id, Bot.uin)
            nickname = info.card ?? info.nickname
        }
        let userInfo = {user_id: Bot.uin, nickname}
        let replyMessage = [{...userInfo, message: '以下是bot的主人列表QAQ'}]
        replyMessage.push({...userInfo, message: msg})

        if (e.isGroup) {
            replyMessage = await e.group.makeForwardMsg(replyMessage)
        } else {
            replyMessage = await e.friend.makeForwardMsg(replyMessage)
        }

        replyMessage.data = replyMessage.data
            .replace(/\n/g, '')
            .replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___')
            .replace(/___+/, '<title>主人列表</title>')

        await e.reply(replyMessage)

        return false;
    }

    // 增加主人
    async addMaster(e) {

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster

        if (e.user_id !== absoluteMaster) {
            if (!e.isGroup) {
                e.reply(`身份验证失败~`)
            }
            return false
        }

        let otherConfig = await Yaml.read(mainOtherConfigPath)
        let masterQQList = otherConfig.masterQQ
        let pushIDString = ''
        let pushIDCount = 0

        for (let i = 0; i < e.message.length; i++) {
            let messageItem = e.message[i]
            let shouldPushID
            if (messageItem.type === 'text') {
                if (messageItem.text.indexOf('增加主人') === -1) {
                    continue;
                }
                let matchResult = messageItem.text.replace(/增加主人/g, "").trim().match(/[1-9]\d*/g)
                if (!matchResult) {
                    continue;
                }
                shouldPushID = parseInt(matchResult[0])
            } else if (messageItem.type === 'at') {
                shouldPushID = messageItem.qq
            }

            if (masterQQList.indexOf(shouldPushID) === -1) {
                masterQQList.push(shouldPushID)
                pushIDString += `${shouldPushID} `
                pushIDCount++
            }
        }

        if (pushIDCount === 0) {
            let msg = '本次并无新的主人被增加'
            if (e.isGroup) {
                e.reply([segment.at(e.user_id), msg])
            } else {
                e.reply(msg)
            }

            return false
        }

        otherConfig.masterQQ = masterQQList
        Yaml.write(mainOtherConfigPath, otherConfig);

        let msg = `${pushIDString}已增加进主人列表！可以发送【主人列表】查看哦~`

        if (e.isGroup) {
            e.reply([segment.at(e.user_id), msg])
        } else {
            e.reply(msg)
        }

        return false;
    }

    // 删除主人
    async delMaster(e) {

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster

        if (e.user_id !== absoluteMaster) {
            if (!e.isGroup) {
                e.reply(`身份验证失败~`)
            }
            return false
        }

        let otherConfig = await Yaml.read(mainOtherConfigPath)
        let masterQQList = otherConfig.masterQQ
        let popIDList = []
        let popIDString = ''
        let popIDCount = 0

        for (let i = 0; i < e.message.length; i++) {
            let messageItem = e.message[i]
            let shouldPopID
            if (messageItem.type === 'text') {
                if (messageItem.text.indexOf('增加主人') === -1) {
                    continue;
                }
                shouldPopID = parseInt(messageItem.text.replace(/增加主人/g, "").trim().match(/[1-9]\d*/g)[0])
                popIDList.push(shouldPopID)
            } else if (messageItem.type === 'at') {
                shouldPopID = messageItem.qq
                popIDList.push(shouldPopID)
            }

            if (masterQQList.indexOf(shouldPopID) >= 0) {
                popIDString += `${shouldPopID} `
                popIDCount++
            }
        }

        if (popIDCount === 0) {
            let msg = '本次并无主人被删除'
            if (e.isGroup) {
                e.reply([segment.at(e.user_id), msg])
            } else {
                e.reply(msg)
            }

            return false
        }

        otherConfig.masterQQ = _.difference(masterQQList, popIDList)
        Yaml.write(mainOtherConfigPath, otherConfig);

        let msg = `${popIDString}已被踢出主人列表！可以发送【主人列表】查看哦~`

        if (e.isGroup) {
            e.reply([segment.at(e.user_id), msg])
        } else {
            e.reply(msg)
        }

        return false;
    }

    // 删除所有主人
    async delAllMaster(e) {

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster

        if (e.user_id !== absoluteMaster) {
            if (!e.isGroup) {
                e.reply(`身份验证失败~`)
            }
            return false
        }

        let otherConfig = await Yaml.read(mainOtherConfigPath)
        otherConfig.masterQQ = [absoluteMaster]
        Yaml.write(mainOtherConfigPath, otherConfig);

        let msg = `已清空除您之外的全部主人！可以发送【主人列表】查看哦~`

        if (e.isGroup) {
            e.reply([segment.at(e.user_id), msg])
        } else {
            e.reply(msg)
        }

        return false;
    }

    // 查看互殴设置
    async getConfig(e) {

        let appConfig = await Yaml.read(appConfigPath)
        let absoluteMaster = appConfig.absoluteMaster
        let botName = appConfig.botName
        let hitMaster = appConfig.hitMaster
        let enableGroup = appConfig.enableGroup
        let onlyMe = appConfig.onlyMe
        let crazyGroup = appConfig.crazyGroup
        let maxHitTimes = appConfig.maxHitTimes
        let abuseType = appConfig.abuseType
        let arsehole = appConfig.arsehole

        if (e.user_id !== absoluteMaster) {
            if (!e.isGroup) {
                e.reply(`身份验证失败~`)
            }
            return false
        }

        let enableGroupString = ''
        for (let item of enableGroup) {
            enableGroupString += `\n　　${item}`
        }
        if (!enableGroupString) {
            enableGroupString = '无'
        }

        let crazyGroupString = ''
        for (let item of crazyGroup) {
            crazyGroupString += `\n　　${item}`
        }
        if (!crazyGroupString) {
            crazyGroupString = '无'
        }

        let abuseTypeString = ''
        if (abuseType === 1) {
            abuseTypeString = '可爱'
        } else if (abuseType === 2) {
            abuseTypeString = '正常'
        } else if (abuseType === 3) {
            abuseTypeString = '暴躁'
        }

        let msg = ''
        msg += '---------------------------------\n'
        msg += `　绝对主人：${absoluteMaster}\n`
        msg += '---------------------------------\n'
        msg += `　bot名字：${botName}\n`
        msg += '---------------------------------\n'
        msg += `　是否打主人：${hitMaster ? '是' : '否'}\n`
        msg += '---------------------------------\n'
        msg += `　启用群列表：${enableGroupString}\n`
        msg += '---------------------------------\n'
        msg += `　打人仅我可用：${onlyMe ? '是' : '否'}\n`
        msg += '---------------------------------\n'
        msg += `　疯狂模式的群：${crazyGroupString}\n`
        msg += '---------------------------------\n'
        msg += `　最大打拳次数：${maxHitTimes}\n`
        msg += '---------------------------------\n'
        msg += `　骂人模式：${abuseTypeString}\n`
        msg += '---------------------------------\n'
        msg += `　跟屁虫：${arsehole ? '开' : '关'}\n`
        msg += '---------------------------------\n'

        e.reply(msg)

        return false;
    }
}
